<template>
  <div class="repair-submit">
    <van-nav-bar
      :title="$t('repair.submit.title')"
      left-arrow
      @click-left="onClickLeft"
    />
    
    <!-- 步骤指示器 -->
    <StepIndicator :steps="steps" :current-step="currentStep" />
    
    <!-- 步骤内容 -->
    <div class="step-content">
      <!-- Step 1: 服务类型 -->
      <div v-show="currentStep === 1" class="step-panel">
        <div class="panel-title">{{ $t('repair.submit.serviceType.title') }}</div>
        <van-radio-group v-model="formData.serviceType">
          <div 
            class="service-card"
            :class="{ active: formData.serviceType === 'IN_STORE' }"
            @click="formData.serviceType = 'IN_STORE'"
          >
            <van-icon name="shop-o" class="card-icon" />
            <div class="card-content">
              <div class="card-title">{{ $t('repair.submit.serviceType.inStore') }}</div>
              <div class="card-desc">{{ $t('repair.submit.serviceType.inStoreDesc') }}</div>
            </div>
            <van-radio name="IN_STORE" />
          </div>
          
          <div 
            class="service-card"
            :class="{ active: formData.serviceType === 'MAIL_IN' }"
            @click="formData.serviceType = 'MAIL_IN'"
          >
            <van-icon name="logistics" class="card-icon" />
            <div class="card-content">
              <div class="card-title">{{ $t('repair.submit.serviceType.mailIn') }}</div>
              <div class="card-desc">{{ $t('repair.submit.serviceType.mailInDesc') }}</div>
            </div>
            <van-radio name="MAIL_IN" />
          </div>
          
          <div 
            class="service-card"
            :class="{ active: formData.serviceType === 'ON_SITE' }"
            @click="formData.serviceType = 'ON_SITE'"
          >
            <van-icon name="user-o" class="card-icon" />
            <div class="card-content">
              <div class="card-title">{{ $t('repair.submit.serviceType.onSite') }}</div>
              <div class="card-desc">{{ $t('repair.submit.serviceType.onSiteDesc') }}</div>
            </div>
            <van-radio name="ON_SITE" />
          </div>
        </van-radio-group>
      </div>
      
      <!-- Step 2: 设备信息 -->
      <div v-show="currentStep === 2" class="step-panel">
        <van-form>
          <van-field
            v-model="formData.deviceModel"
            :label="$t('repair.submit.deviceInfo.model')"
            :placeholder="$t('repair.submit.deviceInfo.modelPlaceholder')"
            required
            readonly
            is-link
            @click="showModelPicker = true"
          />
          
          <van-field
            v-model="formData.deviceSn"
            :label="$t('repair.submit.deviceInfo.sn')"
            :placeholder="$t('repair.submit.deviceInfo.snPlaceholder')"
            required
          >
            <template #button>
              <van-button size="small" type="primary" @click="scanSN">
                {{ $t('repair.submit.deviceInfo.snScan') }}
              </van-button>
            </template>
          </van-field>
          
          <van-field
            v-model="formData.purchaseDate"
            :label="$t('repair.submit.deviceInfo.purchaseDate')"
            :placeholder="$t('repair.submit.deviceInfo.purchaseDatePlaceholder')"
            readonly
            is-link
            @click="showDatePicker = true"
          />
          
          <div class="form-section">
            <div class="form-label">{{ $t('repair.submit.deviceInfo.warrantyStatus') }}</div>
            <van-radio-group v-model="formData.warrantyStatus">
              <van-radio name="IN_WARRANTY">
                {{ $t('repair.submit.deviceInfo.inWarranty') }}
              </van-radio>
              <van-radio name="OUT_WARRANTY">
                {{ $t('repair.submit.deviceInfo.outWarranty') }}
              </van-radio>
              <van-radio name="UNKNOWN">
                {{ $t('repair.submit.deviceInfo.unknown') }}
              </van-radio>
            </van-radio-group>
          </div>
        </van-form>
      </div>
      
      <!-- Step 3: 故障描述 -->
      <div v-show="currentStep === 3" class="step-panel">
        <van-form>
          <div class="form-section">
            <div class="form-label">
              <span class="required">*</span>
              {{ $t('repair.submit.faultDesc.type') }}
            </div>
            <van-checkbox-group v-model="formData.faultTypes">
              <van-checkbox name="POWER_ISSUE">
                {{ $t('repair.submit.faultDesc.powerIssue') }}
              </van-checkbox>
              <van-checkbox name="SCREEN_ISSUE">
                {{ $t('repair.submit.faultDesc.screenIssue') }}
              </van-checkbox>
              <van-checkbox name="BATTERY_ISSUE">
                {{ $t('repair.submit.faultDesc.batteryIssue') }}
              </van-checkbox>
              <van-checkbox name="BUTTON_ISSUE">
                {{ $t('repair.submit.faultDesc.buttonIssue') }}
              </van-checkbox>
              <van-checkbox name="OTHER_ISSUE">
                {{ $t('repair.submit.faultDesc.otherIssue') }}
              </van-checkbox>
            </van-checkbox-group>
          </div>
          
          <van-field
            v-model="formData.faultDescription"
            :label="$t('repair.submit.faultDesc.description')"
            :placeholder="$t('repair.submit.faultDesc.descPlaceholder')"
            type="textarea"
            rows="4"
            maxlength="500"
            show-word-limit
            required
          />
          
          <van-field :label="$t('repair.submit.faultDesc.photos')">
            <template #input>
              <van-uploader
                v-model="fileList"
                multiple
                :max-count="9"
                :after-read="afterRead"
              >
                <van-button icon="photograph" type="primary" size="small">
                  {{ $t('repair.submit.faultDesc.uploadPhoto') }}
                </van-button>
              </van-uploader>
              <div class="upload-tip">{{ $t('repair.submit.faultDesc.photosDesc') }}</div>
            </template>
          </van-field>
        </van-form>
      </div>
      
      <!-- Step 4: 服务方式 -->
      <div v-show="currentStep === 4" class="step-panel">
        <van-form>
          <van-field
            v-if="formData.serviceType === 'IN_STORE' || formData.serviceType === 'ON_SITE'"
            v-model="formData.serviceCenterName"
            :label="$t('repair.submit.serviceMethod.selectCenter')"
            :placeholder="$t('repair.submit.serviceMethod.selectCenterPlaceholder')"
            required
            readonly
            is-link
            @click="selectServiceCenter"
          />
          
          <van-field
            v-if="formData.serviceType === 'ON_SITE'"
            v-model="formData.appointmentTime"
            :label="$t('repair.submit.serviceMethod.appointmentTime')"
            :placeholder="$t('repair.submit.serviceMethod.appointmentTimePlaceholder')"
            required
            readonly
            is-link
            @click="showTimePicker = true"
          />
          
          <van-field
            v-model="formData.contactPhone"
            :label="$t('repair.submit.serviceMethod.contactPhone')"
            :placeholder="$t('repair.submit.serviceMethod.contactPhonePlaceholder')"
            type="tel"
            required
          />
          
          <van-field
            v-model="formData.contactName"
            :label="$t('repair.submit.serviceMethod.contactName')"
            :placeholder="$t('repair.submit.serviceMethod.contactNamePlaceholder')"
            required
          />
        </van-form>
      </div>
      
      <!-- Step 5: 确认提交 -->
      <div v-show="currentStep === 5" class="step-panel">
        <div class="confirm-section">
          <div class="section-title">{{ $t('repair.submit.confirm.orderInfo') }}</div>
          <van-cell-group inset>
            <van-cell :title="$t('repair.submit.confirm.serviceType')" :value="getServiceTypeText()" />
            <van-cell :title="$t('repair.submit.confirm.deviceModel')" :value="formData.deviceModel" />
            <van-cell :title="$t('repair.submit.confirm.faultType')" :value="getFaultTypesText()" />
            <van-cell v-if="formData.serviceCenterName" :title="$t('repair.submit.confirm.serviceCenter')" :value="formData.serviceCenterName" />
            <van-cell v-if="formData.appointmentTime" :title="$t('repair.submit.confirm.appointmentTime')" :value="formData.appointmentTime" />
            <van-cell :title="$t('repair.submit.confirm.contactPhone')" :value="formData.contactPhone" />
          </van-cell-group>
        </div>
        
        <div class="confirm-section">
          <div class="section-title">{{ $t('repair.submit.confirm.estimatedCost') }}</div>
          <van-cell-group inset>
            <van-cell :title="$t('repair.submit.confirm.detectionFee')" :value="$t('repair.submit.confirm.free')" />
            <van-cell :label="$t('repair.submit.confirm.costNote')" />
          </van-cell-group>
        </div>
        
        <div class="agreement">
          <van-checkbox v-model="formData.agreedToTerms">
            {{ $t('repair.submit.confirm.agreement') }}
            <span class="agreement-link">{{ $t('repair.submit.confirm.agreementLink') }}</span>
          </van-checkbox>
        </div>
      </div>
    </div>
    
    <!-- 底部按钮 -->
    <div class="footer-buttons">
      <van-button v-if="currentStep > 1" block @click="prevStep">
        {{ $t('repair.common.prev') }}
      </van-button>
      <van-button 
        v-if="currentStep < 5" 
        type="primary" 
        block 
        :disabled="!canGoNext"
        @click="nextStep"
      >
        {{ $t('repair.common.next') }}
      </van-button>
      <van-button 
        v-if="currentStep === 5" 
        type="primary" 
        block 
        :disabled="!canGoNext"
        :loading="submitting"
        @click="submitOrder"
      >
        {{ $t('repair.submit.confirm.submitButton') }}
      </van-button>
    </div>
    
    <!-- 设备型号选择器 -->
    <van-popup v-model:show="showModelPicker" position="bottom">
      <van-picker
        :columns="modelColumns"
        @confirm="onModelConfirm"
        @cancel="showModelPicker = false"
      />
    </van-popup>
    
    <!-- 日期选择器 -->
    <van-popup v-model:show="showDatePicker" position="bottom">
      <van-date-picker
        :min-date="minDate"
        :max-date="maxDate"
        @confirm="onDateConfirm"
        @cancel="showDatePicker = false"
      />
    </van-popup>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useI18n } from 'vue-i18n'
import { showToast, showSuccessToast, showLoadingToast, closeToast, showDialog } from 'vant'
import { useRepairStore } from '@/stores/repair'
import { submitRepairOrder, uploadFaultImage } from '@/api/repair'
import StepIndicator from './components/StepIndicator.vue'

const router = useRouter()
const { t } = useI18n()
const repairStore = useRepairStore()

// 步骤
const steps = [
  t('repair.submit.step1'),
  t('repair.submit.step2'),
  t('repair.submit.step3'),
  t('repair.submit.step4'),
  t('repair.submit.step5')
]

// 当前步骤
const currentStep = computed(() => repairStore.currentStep)

// 表单数据
const formData = computed(() => repairStore.formData)

// 是否可以下一步
const canGoNext = computed(() => repairStore.canGoNext)

// 提交中
const submitting = ref(false)

// 设备型号选择
const showModelPicker = ref(false)
const modelColumns = [
  { text: 'JetWave Pro 2024', value: 'JetWave Pro 2024' },
  { text: 'JetWave Mini 2024', value: 'JetWave Mini 2024' },
  { text: 'JetWave Max 2024', value: 'JetWave Max 2024' }
]

// 日期选择
const showDatePicker = ref(false)
const minDate = new Date(2020, 0, 1)
const maxDate = new Date()

// 时间选择
const showTimePicker = ref(false)

// 图片上传
const fileList = ref([])

// 返回
const onClickLeft = () => {
  if (currentStep.value > 1) {
    showDialog({
      title: t('repair.common.confirm'),
      message: '确定要退出吗？已填写的内容将保存为草稿',
    }).then(() => {
      repairStore.saveDraft()
      router.back()
    })
  } else {
    router.back()
  }
}

// 下一步
const nextStep = () => {
  repairStore.nextStep()
  repairStore.saveDraft()
}

// 上一步
const prevStep = () => {
  repairStore.prevStep()
}

// 确认设备型号
const onModelConfirm = ({ selectedOptions }) => {
  const selectedValue = selectedOptions[0]?.value || selectedOptions[0]
  repairStore.updateFormData({ deviceModel: selectedValue })
  showModelPicker.value = false
}

// 确认日期
const onDateConfirm = ({ selectedValues }) => {
  // selectedValues 是一个数组,例如: ['2024', '11', '18']
  const [year, month, day] = selectedValues
  repairStore.updateFormData({ purchaseDate: `${year}-${month}-${day}` })
  showDatePicker.value = false
}

// 扫描SN码
const scanSN = () => {
  showToast('扫码功能开发中')
}

// 选择服务中心
const selectServiceCenter = () => {
  router.push('/repair/service-centers')
}

// 图片上传
const afterRead = async (file) => {
  showLoadingToast({
    message: t('repair.common.loading'),
    forbidClick: true,
    duration: 0
  })
  
  try {
    const res = await uploadFaultImage(file.file)
    repairStore.addFaultPhoto(res.data.url)
    closeToast()
    showSuccessToast('上传成功')
  } catch (error) {
    closeToast()
    showToast('上传失败')
  }
}

// 获取服务类型文本
const getServiceTypeText = () => {
  const typeMap = {
    'IN_STORE': t('repair.submit.serviceType.inStore'),
    'MAIL_IN': t('repair.submit.serviceType.mailIn'),
    'ON_SITE': t('repair.submit.serviceType.onSite')
  }
  return typeMap[formData.value.serviceType] || ''
}

// 获取故障类型文本
const getFaultTypesText = () => {
  const typeMap = {
    'POWER_ISSUE': t('repair.submit.faultDesc.powerIssue'),
    'SCREEN_ISSUE': t('repair.submit.faultDesc.screenIssue'),
    'BATTERY_ISSUE': t('repair.submit.faultDesc.batteryIssue'),
    'BUTTON_ISSUE': t('repair.submit.faultDesc.buttonIssue'),
    'OTHER_ISSUE': t('repair.submit.faultDesc.otherIssue')
  }
  return formData.value.faultTypes.map(type => typeMap[type]).join('、')
}

// 提交工单
const submitOrder = async () => {
  submitting.value = true
  
  try {
    const res = await submitRepairOrder(formData.value)
    showSuccessToast(t('repair.submit.success.message'))
    
    // 清除草稿
    repairStore.clearDraft()
    
    // 跳转到详情页
    setTimeout(() => {
      router.replace(`/repair/track/${res.data.caseNo}`)
    }, 1500)
  } catch (error) {
    showToast('提交失败，请重试')
  } finally {
    submitting.value = false
  }
}

// 加载草稿
onMounted(() => {
  repairStore.loadDraft()
})
</script>

<style scoped lang="scss">
.repair-submit {
  min-height: 100vh;
  background: linear-gradient(180deg, #f0f9ff 0%, #f7f8fa 100%);
  padding-bottom: 80px;
}

.step-content {
  padding: 16px;
}

.step-panel {
  background: #fff;
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.06);
  animation: slideUp 0.3s ease-out;
}

@keyframes slideUp {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.panel-title {
  font-size: 17px;
  font-weight: 600;
  color: #323233;
  margin-bottom: 20px;
  position: relative;
  padding-left: 12px;
  
  &::before {
    content: '';
    position: absolute;
    left: 0;
    top: 50%;
    transform: translateY(-50%);
    width: 4px;
    height: 18px;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    border-radius: 2px;
  }
}

.service-card {
  display: flex;
  align-items: center;
  padding: 18px;
  border: 2px solid #ebedf0;
  border-radius: 12px;
  margin-bottom: 12px;
  cursor: pointer;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  background: #fff;
  
  &:last-child {
    margin-bottom: 0;
  }
  
  &.active {
    border-color: #1989fa;
    background: linear-gradient(135deg, #f0f9ff 0%, #e6f7ff 100%);
    box-shadow: 0 4px 12px rgba(25, 137, 250, 0.2);
    transform: translateY(-2px);
  }
  
  &:active {
    transform: scale(0.98);
  }
}

.card-icon {
  font-size: 36px;
  color: #1989fa;
  margin-right: 16px;
  transition: transform 0.3s;
  
  .active & {
    transform: scale(1.1);
  }
}

.card-content {
  flex: 1;
}

.card-title {
  font-size: 16px;
  font-weight: 600;
  color: #323233;
  margin-bottom: 6px;
}

.card-desc {
  font-size: 13px;
  color: #969799;
  line-height: 1.4;
}

.upload-tip {
  font-size: 12px;
  color: #969799;
  margin-top: 12px;
  padding: 8px 12px;
  background: #f7f8fa;
  border-radius: 6px;
  line-height: 1.5;
}

.confirm-section {
  margin-bottom: 20px;
  
  &:last-child {
    margin-bottom: 0;
  }
}

.section-title {
  font-size: 16px;
  font-weight: 600;
  color: #323233;
  margin-bottom: 12px;
  padding: 0 16px;
  position: relative;
  padding-left: 28px;
  
  &::before {
    content: '';
    position: absolute;
    left: 16px;
    top: 50%;
    transform: translateY(-50%);
    width: 4px;
    height: 16px;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    border-radius: 2px;
  }
}

.agreement {
  padding: 16px;
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
}

.agreement-link {
  color: #1989fa;
  font-weight: 500;
}

.footer-buttons {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 12px 16px;
  background: #fff;
  box-shadow: 0 -4px 12px rgba(0, 0, 0, 0.08);
  display: flex;
  gap: 12px;
  z-index: 100;
  
  .van-button {
    flex: 1;
    height: 44px;
    border-radius: 22px;
    font-size: 16px;
    font-weight: 500;
    transition: all 0.3s;
    
    &:active {
      transform: scale(0.96);
    }
  }
}

// 自定义表单区块
.form-section {
  padding: 16px;
  margin-bottom: 12px;
  background: #fff;
}

.form-label {
  font-size: 15px;
  font-weight: 600;
  color: #323233;
  margin-bottom: 16px;
  
  .required {
    color: #ee0a24;
    margin-right: 4px;
  }
}

// 单选框和复选框样式
:deep(.van-radio-group),
:deep(.van-checkbox-group) {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

:deep(.van-radio),
:deep(.van-checkbox) {
  display: flex;
  align-items: center;
  padding: 14px 16px;
  background: #f7f8fa;
  border-radius: 10px;
  margin: 0 !important;
  transition: all 0.3s;
  cursor: pointer;
  
  &:active {
    background: #e8e9eb;
    transform: scale(0.98);
  }
  
  .van-radio__label,
  .van-checkbox__label {
    flex: 1;
    font-size: 14px;
    color: #323233;
    line-height: 1.5;
    margin-left: 12px;
  }
  
  .van-radio__icon,
  .van-checkbox__icon {
    font-size: 20px;
    flex-shrink: 0;
  }
}

// 表单样式优化
:deep(.van-field) {
  padding: 14px 16px;
  
  .van-field__label {
    font-weight: 500;
    color: #323233;
  }
  
  .van-field__control {
    font-size: 15px;
  }
}

:deep(.van-uploader) {
  .van-uploader__wrapper {
    gap: 12px;
  }
  
  .van-uploader__preview,
  .van-uploader__upload {
    border-radius: 8px;
    overflow: hidden;
  }
}
</style>

